package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Fragment2 extends Fragment {

    private RecyclerView recyclerView;
    private List<Map<String, Object>> contactList;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_layout2, container, false);
        recyclerView = view.findViewById(R.id.recyclerViewInFragment);

        // 初始化联系人数据
        int[] avatarIds = {R.drawable.avatar1, R.drawable.avatar2, R.drawable.avatar3, R.drawable.avatar4,R.drawable.avatar5,R.drawable.avatar6,R.drawable.avatar7,R.drawable.avatar8};
        String[] names = {"张三", "李四", "王五", "老板","李六","弟弟","哥哥","姐姐"};
        String[] phones = {"12345678901", "23456789012", "34567890123", "45678901234","46546165","564165","5641846","82316"};

        contactList = new ArrayList<>();
        for (int i = 0; i < avatarIds.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("avatar", avatarIds[i]);
            map.put("name", names[i]);
            map.put("phone", phones[i]);
            contactList.add(map);
        }

        // 设置适配器
        ContactAdapter adapter = new ContactAdapter(contactList);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 设置点击监听器
        adapter.setOnItemClickListener(position -> {
            Map<String, Object> selectedContact = contactList.get(position);

            Intent intent = new Intent(getContext(), ContactActivity.class);
            intent.putExtra("avatar", (Integer) selectedContact.get("avatar"));
            intent.putExtra("name", (String) selectedContact.get("name"));
            intent.putExtra("phone", (String) selectedContact.get("phone"));
            startActivity(intent);
        });

        return view;
    }
}
